package com.service;

import com.dao.FrontUserLocationRepository;
import com.model.FrontUserLocation;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.*;

@Service
@Transactional
public class FrontUserLocationService {
    @Resource
    private FrontUserLocationRepository repository;

    private static ConcurrentMap<Long, FrontUserLocation> saveMap = new ConcurrentHashMap<>();
    private static ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);
    {
        // 2分钟更新一次saveMap
        scheduled.scheduleAtFixedRate(() -> {
            ConcurrentMap<Long, FrontUserLocation> taskSaveMap = saveMap;
            int len = saveMap.size();
            saveMap = new ConcurrentHashMap<>(len);
            taskSaveMap.forEach((userId, location) -> this.saveAndFlush(location));
        },2, 2, TimeUnit.MINUTES);
    }

    public void setSaveMap(FrontUserLocation userLocation) {
        saveMap.put(userLocation.getUserId(), userLocation);
    }

    public FrontUserLocation findOneByUserId(Long userId) {
        return repository.findTopByUserId(userId);
    }

    public boolean saveAndFlush(FrontUserLocation userLocation) {
        // 是否存在
        FrontUserLocation dbUserLocation = repository.findTopByUserId(userLocation.getUserId());
        if(dbUserLocation != null) {
            userLocation.setId(dbUserLocation.getId());
        }
        return repository.saveAndFlush(userLocation) != null;
    }
}
